import requests
from tqdm import tqdm
from pathlib import Path
import sys
import time

def fetch_json(url):
    """从给定的URL获取JSON数据"""
    response = requests.get(url)
    return response.json()


def extract_image_data(json_data):
    """从JSON数据中提取image_prefix和特定的图像名称"""
    # 提取 image_prefix
    image_prefix = json_data['image_prefix']

    # 直接获取特定的图像名称
    target_image_name = json_data['images'][4]['name']
    return image_prefix, target_image_name


def download_file(url, filename):
    """下载文件并显示进度条"""
    response = requests.get(url, stream=True)
    if response.status_code == 200:
        total_size_in_bytes = int(response.headers.get('content-length', 0))
        block_size = 1024  # 1 Kibibyte
        progress_bar = tqdm(total=total_size_in_bytes, unit='iB', unit_scale=True)

        with open(filename, "wb") as file:
            for data in response.iter_content(block_size):
                progress_bar.update(len(data))
                file.write(data)
        progress_bar.close()
        if total_size_in_bytes != 0 and progress_bar.n != total_size_in_bytes:
            print("错误：下载过程中出现问题")
        else:
            print(f"文件已成功下载为 {filename}")
    else:
        print(f"下载文件失败。状态码: {response.status_code}")


def check_existing_zip(target_image_name):
    """检查当前目录下是否存在与target_image_name相匹配的ZIP文件"""
    # 获取当前工作目录
    current_dir = Path.cwd()

    # 构建目标文件路径
    target_file = current_dir / f"{target_image_name}"

    # 检查文件是否存在
    if target_file.exists():
        print(f"找到现有的ZIP文件: {target_file}")
        print("版本是最新的。无需下载。")
        print("程序将在5秒后退出...")
        time.sleep(5)  # 程序将暂停5秒钟
        sys.exit(0)  # 退出脚本
    else:
        print(f"当前目录下未找到名为 {target_image_name} 的ZIP文件")


if __name__ == "__main__":
    url = "https://openwrt.ai/json/v1/releases/targets/x86/64/generic.json"
    json_data = fetch_json(url)

    if json_data:
        # 提取 image_prefix 和特定文件信息
        image_prefix, target_image_name = extract_image_data(json_data)

        if target_image_name:
            print(f"\n最新版本: {image_prefix}")
            print(f"目标文件名: {target_image_name}")

            # 检查当前目录下是否存在与 target_image_name 相匹配的 ZIP 文件
            check_existing_zip(target_image_name)

            # 构建下载链接
            download_url = f"https://dl.openwrt.ai/releases/targets/x86/64/{target_image_name}"
            print(f"下载链接: {download_url}")

            # 下载文件
            download_file(download_url, target_image_name)
            input("更新完成，按任意键退出...")

        else:
            print("未找到目标文件。")
            input("更新失败，按任意键退出...")
